import RNFS from "react-native-fs";
import RNFetchBlob from "react-native-blob-util";
// @ts-ignore
import Ping from "react-native-ping";
import { useDispatch } from "react-redux";
// @ts-ignore
import DialogAndroid from "react-native-dialogs";
import dayjs from "dayjs";

import { params2Obj } from "@/utils";
import { Module } from "@/utils/nativeModules";
import fso from "@/utils/FileOperate/operate";
import sm from "@/utils/ScheduleManage/operate";
import { getEntryNetworkInfo } from "@/utils/entryNetworkInfoOperate";
import { destroy as websocketDestroy, connect as websocketConnect, setWsConnect } from "@/utils/websocket/index";
import store from "@/store";

import Btn from "@/components/Btn";

import config from "@/config";
import globalMethods from "@/GlobalMethodProvider";

import { setCurPlayData } from "@/store/slices";
import { checkAppUpdate } from "@/utils/cron/check";

/** 测试组件 */
const DevComp = () => {
  const dispatch = useDispatch();

  return (
    <>
      <Btn
        type="primary"
        text="测试ping"
        onClick={async () => {
          try {
            // https://github.com/RoJoHub/react-native-ping
            const trafficStats = await Ping.getTrafficStats();
            console.log("网络质量: ", trafficStats);

            // const address = 'www.baidu.com';
            // const address = "www.github.com";
            const address = "127.0.0.1";
            for (let i = 0; i < 10; i++) {
              const start = Date.now();
              const rtt: string = await Ping.start(address, { timeout: 1000 });
              const end = Date.now();
              console.log(`ping ${address} 往返时延=${rtt} 用时=${end - start}ms`);
            }
          } catch (err) {
            console.log("err: ", err);
          }
        }}
      />
      <Btn
        type="primary"
        text="原生代码"
        onClick={async () => {
          try {
            const res2 = await Module.test();
            globalMethods.$success("响应: " + res2);
          } catch (err) {
            console.log("err: ", err);
            globalMethods.$error("发生了错误: " + err);
          } finally {
            DialogAndroid.dismiss();
          }
        }}
      />
      <Btn
        type="primary"
        text="垫片"
        onClick={() => {
          dispatch(
            setCurPlayData({
              filePath: "",
              rawData: null,
              type: "POLYFILL",
              content: "",
              errorText: "",
              width: 0,
              height: 0
            })
          );
        }}
      />
      <Btn
        type="primary"
        text="异常播放"
        onClick={() => {
          dispatch(
            setCurPlayData({
              filePath: "",
              rawData: null,
              type: "4",
              content: "",
              errorText: "这个是测试的错误文本",
              width: 0,
              height: 0
            })
          );
        }}
      />
      <Btn
        type="primary"
        text="执行shell(非ROOT)"
        onClick={async () => {
          try {
            const { action, text } = await DialogAndroid.prompt("执行shell", "输入需要执行的shell", {
              defaultValue: "uname -a",
              cancelable: false
            });

            if (action === DialogAndroid.actionPositive) {
              if (text) {
                const res = await Module.execShell(text, false);
                fso.info("执行 shell 命令: ", text);
                fso.info("shell 命令输出: ", res);
                if (res) {
                  if (res.exitValue === 0) {
                    globalMethods.$showMessage({
                      type: "toast",
                      message: "执行成功: " + res?.stdout
                    });
                  } else {
                    globalMethods.$showMessage({
                      type: "toast",
                      message: "执行失败: " + res?.stderr
                    });
                  }
                }
              } else {
                globalMethods.$warning("执行的命令不能为空");
              }
            }
          } catch (err) {
            console.log("err: ", err);
            globalMethods.$error("发生了错误: " + err);
          }
        }}
      />
      <Btn
        type="primary"
        text="执行shell(ROOT)"
        onClick={async () => {
          try {
            const { action, text } = await DialogAndroid.prompt("执行shell", "输入需要执行的shell", {
              // pm install -r /storage/emulated/0/Download/mlkj-m180/apks/test.apk
              // date 101213352020.39 set
              defaultValue:
                "/system/bin/screencap -p /storage/emulated/0/Download/mlkj-m180/screenshot/1709001798460.jpg",
              cancelable: false
            });

            if (action === DialogAndroid.actionPositive) {
              if (text) {
                const res = await Module.execShell(text, true);
                fso.info("执行 shell 命令: ", text);
                fso.info("shell 命令输出: ", res);
                if (res) {
                  if (res.exitValue === 0) {
                    globalMethods.$showMessage({
                      type: "toast",
                      message: "执行成功: " + res?.stdout
                    });
                  } else {
                    globalMethods.$showMessage({
                      type: "toast",
                      message: "执行失败: " + res?.stderr
                    });
                  }
                }
              } else {
                globalMethods.$warning("执行的命令不能为空");
              }
            }
          } catch (err) {
            console.log("err: ", err);
            globalMethods.$error("发生了错误: " + err);
          }
        }}
      />

      <Btn
        type="primary"
        text="同步排期"
        onClick={() => {
          globalMethods.$showLoading("同步排期中");
          sm.syncSchedule()
            .then(res => {
              if (res) {
                sm.loopSeek();
              } else {
                fso.error("排期数据同步失败");
              }
            })
            .finally(() => {
              globalMethods.$hideLoading();
            });
        }}
      />
      <Btn
        type="primary"
        text="上传当天日志"
        onClick={async () => {
          try {
            const time = dayjs().format("YYYY_MM_DD");
            const { action, text } = await DialogAndroid.prompt("上传日志", "输入上传日志的接口地址", {
              defaultValue: `${config.serveUrl.localhostServe}/uploadFile`,
              cancelable: false
            });

            if (action === DialogAndroid.actionPositive) {
              DialogAndroid.showProgress("文件上传中, 请稍等...", {
                style: DialogAndroid.circular
              });

              const filePath = fso.getTodayFile();
              const isExists = await RNFS.exists(filePath);
              if (!isExists) {
                globalMethods.$warning("文件不存在: " + filePath);
                return;
              }

              const res = await fso.uploadFile({
                url: text,
                method: "POST",
                fileName: `${time}.log`,
                filePath,
                formDataKey: "file"
              });
              console.log("res: ", res);

              globalMethods.$success("上传成功");
            }
          } catch (err) {
            console.log("err: ", err);
            globalMethods.$error("发生了错误: " + err);
          } finally {
            DialogAndroid.dismiss();
          }
        }}
      />
      <Btn
        type="primary"
        text="下载APK"
        onClick={async () => {
          try {
            const time = dayjs().format("YYYY_MM_DD");
            const { action, text } = await DialogAndroid.prompt("下载APK", "输入APK文件下载地址", {
              // defaultValue: `${config.serveUrl.localhostServe}/downloadFile?file=mlkj_m180_app_0.0.1_2024_04_09.apk`,
              defaultValue: `${config.serveUrl.localhostServe}/downloadFile?file=__UNI__B9CBD23_1017173613_126.apk`,
              cancelable: false
            });

            if (action === DialogAndroid.actionPositive) {
              DialogAndroid.showProgress("文件下载中, 请稍等...", {
                style: DialogAndroid.circular // DialogAndroid.progressHorizontal
              });

              const paramsObj = params2Obj<{ file: string }>({
                str: text,
                decode: false
              });

              if (!paramsObj) {
                globalMethods.$warning("参数异常");
                DialogAndroid.dismiss();
                return;
              }

              const downFileToNativePath = fso.apksDir + `/${paramsObj.file}`;
              // const downFileToNativePath = `${RNFS.DocumentDirectoryPath}/${paramsObj.file}`;

              // 删除旧的安装包
              const isExists = await RNFS.exists(downFileToNativePath);
              if (isExists) {
                await RNFS.unlink(downFileToNativePath);
              }

              const filePath = await fso.downFile({
                method: "GET",
                url: text,
                downFileToNativePath
              });
              console.log("filePath: ", filePath);
              if (typeof filePath === "string") {
                const res = await Module.actionViewIntent(filePath, "apk");
                globalMethods.$success("安装响应: " + res);
                fso.info("安装响应: ", res);
              } else {
                globalMethods.$warning("安装失败");
              }

              // TODO 删除安装包
              // await fso.rm(filePath);
            }
          } catch (err) {
            console.log("err: ", err);
            globalMethods.$error("发生了错误: " + err);
          } finally {
            DialogAndroid.dismiss();
          }
        }}
      />
      <Btn
        type="primary"
        text="入网信息"
        onClick={() => {
          getEntryNetworkInfo().then(res => {
            console.log("res: ", res);
          });
        }}
      />
      <Btn
        type="primary"
        text="已下载素材信息"
        onClick={async () => {
          try {
            const list = await sm.getDownloadedMaterial();
            const paths = list.map(e => e.path);
            console.log("paths: ", paths);
          } catch (err) {
            console.log("err: ", err);
            globalMethods.$error("发生了错误: " + err);
          }
        }}
      />
      <Btn
        type="primary"
        text="生成配置文件"
        onClick={async () => {
          try {
            const configFile = `${fso.baseDir}/CONFIG.json`;
            await RNFS.writeFile(
              configFile,
              JSON.stringify({
                platformBaseUrl: "http://127.0.0.1:8900",
                proxyUrl: "http://127.0.0.1:8900",
                websocketUrl: "ws:127.0.0.1:8100/ws-test"
              })
            );
          } catch (err) {
            console.log("err: ", err);
            globalMethods.$error("发生了错误: " + err);
          }
        }}
      />
      <Btn
        type="primary"
        text="测试定时器"
        onClick={async () => {
          setInterval(() => {
            console.log("1s 执行");
          }, 1000);
        }}
      />
      <Btn
        type="primary"
        text="下载文件"
        onClick={async () => {
          const url = `http://20.165.8.158:8000/m000/minio/pos/down/m180/af09668fdcb5dc7458f531a362290b01.mp4?name=10.金融服务新市民 畅享美好新生活.mp4`;

          const dir = `${fso.resourceDir}/test`;
          const filePath = `${dir}/hello.mp4`;
          const exists = await RNFS.exists(dir);
          if (!exists) await RNFS.mkdir(dir);

          const task = RNFetchBlob.config({
            path: filePath,
            fileCache: true
          })
            .fetch("GET", url, {})
            // 下载进度
            .progress({ interval: 1500 }, (received, total) => {
              if (Number(received) === 0 && Number(total) === -1) {
                console.log(`无法计算下载进度: received: ${received}, total: ${total}`, url);
              } else {
                const progress = (Number(received) / Number(total)) * 100;
                console.log(`下载进度: ${progress.toFixed(2)}% -> ${url}`);
              }
            });

          task
            .then(res => {
              console.log("下载成功: ", res);
            })
            .catch(err => {
              console.log("下载失败: ", err);
            });
        }}
      />
      <Btn
        type="primary"
        text="下载文件2s后自动停止"
        onClick={async () => {
          fso.downFile(
            {
              url: "http://localhost:8100/nginx-images/dk1.mp4",
              method: "GET",
              description: "测试下载",
              downFileToNativePath: `${fso.baseDir}/dk1.mp4`
            },
            task => {
              console.log("当前的下载任务实例: ", task);
              setTimeout(() => {
                console.log("取消下载");
                task.cancel();
              }, 2000);
            }
          );
        }}
      />
      <Btn
        type="primary"
        text="批量下载文件2s后全部取消"
        onClick={async () => {
          sm.downMaterialData({
            materialList: [
              // @ts-ignore
              {
                downFileToNativePath: `${fso.resourceDir}/1.mp4`,
                downFileUrl: "http://1.12.69.30:9000/m180/2024/04/6c4c8622db7d7121eb045e028d0e08df.mp4",
                name: "1"
              },
              // @ts-ignore
              {
                downFileToNativePath: `${fso.resourceDir}/2.mp4`,
                downFileUrl: "http://1.12.69.30:9000/m180/2024/04/7af3d99bb8b0652a8729609aece2128d.mp4",
                name: "2"
              },
              // @ts-ignore
              {
                downFileToNativePath: `${fso.resourceDir}/3.mp4`,
                downFileUrl: "http://1.12.69.30:9000/m180/2024/04/e09617bf713e42bb7ec990d049de245d.mp4",
                name: "3"
              },
              // @ts-ignore
              {
                downFileToNativePath: `${fso.resourceDir}/4.png`,
                downFileUrl: "http://1.12.69.30:9000/m180/2024/04/97815ae55e2db83b307617f978c5a12d.png",
                name: "4"
              }
            ]
          });

          setTimeout(() => {
            sm.cancelDownMaterial();
          }, 2000);
        }}
      />

      <Btn
        type="primary"
        text="重连websocket"
        onClick={async () => {
          try {
            if (store.getState().index.isWebsocketConnect) {
              // 销毁websocket, 会导致连接关闭
              websocketDestroy();
              setWsConnect(false);
            }
            setTimeout(() => {
              websocketConnect();
              console.log("重新连接");
            }, 500);
          } catch (err) {
            fso.error("发生了错误: ", err);
          }
        }}
      />
      <Btn
        type="primary"
        text="是否是旧系统迁移"
        onClick={() => {
          sm.isOldAppMigration()
            .then(res => {
              console.log("res: ", res);
            })
            .catch(err => {
              console.log("err: ", err);
            });
        }}
      />
      <Btn
        type="primary"
        text="检查离线升级指令"
        onClick={() => {
          checkAppUpdate();
        }}
      />

      <Btn
        type="primary"
        text="root写入文件"
        onClick={async () => {
          console.log("fso: ", fso);
          const filePath = `/data/user/0/com.mlkj.mip/files`;

          Module.execShell(`echo ${filePath}/hello.txt abcd`, true)
            .then(res => {
              console.log("res: ", res);
            })
            .catch(err => {
              console.log("err: ", err);
            });
        }}
      />
    </>
  );
};

export default DevComp;
